/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package supermarket;

/**
 *
 * @author aggelos
 */
import javax.swing.JOptionPane;
import model.*;

public class LoginForm extends javax.swing.JFrame {

    private static final long serialVersionUID = 1L;

    /**
     * Creates new form LoginForm
     */
    public LoginForm() {
        initComponents();
        //make the window startup position be centered
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        username = new javax.swing.JTextField();
        Button_ok = new javax.swing.JButton();
        Button_Cancel = new javax.swing.JButton();
        userpassword = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ΕΦΑΡΜΟΓΗ  SUPER-MARKET ");
        setIconImages(null);
        setName("loginfrm"); // NOI18N
        setResizable(false);

        jLabel1.setText("Δώστε τα στοιχεία εισόδου");

        jLabel2.setText("User Name :");

        jLabel3.setText("Password   :");

        username.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usernameActionPerformed(evt);
            }
        });

        Button_ok.setText("OK");
        Button_ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Button_okActionPerformed(evt);
            }
        });

        Button_Cancel.setText("Ακυρο");
        Button_Cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Button_CancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addGap(18, 18, 18)
                            .addComponent(username))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                                    .addComponent(Button_ok, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(50, 50, 50)
                                    .addComponent(Button_Cancel))
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(20, 20, 20)
                                    .addComponent(userpassword))))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(userpassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Button_Cancel)
                    .addComponent(Button_ok))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void Button_okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button_okActionPerformed
        // Διάβασε username & Pass
        String user = this.username.getText();
        String pass = new String(userpassword.getPassword());

        // Αν δεν έχουν τίποτα γραμμένο exit
        if (user.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Το όνομα χρήστη είναι κενό", "Σφάλμα", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (pass.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Ο Κωδικός είναι κενός", "Σφάλμα", JOptionPane.WARNING_MESSAGE);

            return;
        }

        // Ελεγξε αν τα στοιχεία υπάρχουν στην βάση
        DBmanager db = new DBmanager();
        int id = db.login(user, pass);
        // εαν int id >0 o χρήστης ταυτοποιήθηκε

        // Δες αν είναι πελάτης ή Admin
        if (id > 0) {
            Customer c = db.getCustomerById(id);
            // Από εργασία 2, welcome message
            // Από εργασία 3, success Login

            if (c.getIsAdmin()) {
                // ανοιξε φόρμα admin
                JOptionPane.showMessageDialog(this, SuperMarket.msgSuccessLogin + "\n" + SuperMarket.msgWelcome + c.getFirstName() + " " + c.getLastName(), SuperMarket.appTitle, JOptionPane.PLAIN_MESSAGE);
            } else {
                // ανοιξε φόρμα πελάτη
                JOptionPane.showMessageDialog(this, SuperMarket.msgSuccessLogin + "\n" + SuperMarket.msgWelcome + c.getFirstName() + " " + c.getLastName(), SuperMarket.appTitle, JOptionPane.PLAIN_MESSAGE);
            }
            //Ανοιξε Κεντρική φόρμα
            MainForm mainForm = new MainForm(db, c);
            //make the window startup position be centered
            mainForm.setLocationRelativeTo(null);
            // Δείξε την νέα φόρμα
            mainForm.setVisible(true);

            // κλείσε την login φόρμα
            dispose();

        } else {
            //τύπωσε μυνήματα λάθους
            if (id == -3) {
                JOptionPane.showMessageDialog(this, SuperMarket.msgTryLater, SuperMarket.msgDialogTitle, JOptionPane.WARNING_MESSAGE);
            }
            if (id == -1) {
                JOptionPane.showMessageDialog(this, SuperMarket.msgUnknowUser, SuperMarket.msgDialogTitle, JOptionPane.WARNING_MESSAGE);
            }
            if (id == -2) {
                JOptionPane.showMessageDialog(this, SuperMarket.msgWrongPass, SuperMarket.msgDialogTitle, JOptionPane.WARNING_MESSAGE);
            }
        }
    }//GEN-LAST:event_Button_okActionPerformed

    private void usernameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usernameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_usernameActionPerformed

    private void Button_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button_CancelActionPerformed
        // κατέστρεψε το παράθυρο
        dispose();
        // Τερμάτισε την εφαρμογή
        System.exit(0);
    }//GEN-LAST:event_Button_CancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            //=============================================================
            // Clean and Populate Database
            //=============================================================
            // DBmanager DBM = new DBmanager();
            //   DBM.clearDB();
            //   DBM.createStoresAndProducts();
           //    DBM.createCustomersAndChecks();// Also root user
            //=============================================================


            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new LoginForm().setVisible(true);
                }
            });

        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }




    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Button_Cancel;
    private javax.swing.JButton Button_ok;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField username;
    private javax.swing.JPasswordField userpassword;
    // End of variables declaration//GEN-END:variables
}
